import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  message,
  Popconfirm,
  Card,
  TreeSelect,
  type TableColumnsType,
} from '@nbase/ui';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@nbase/ui/icons';
import { deptService, type Dept, type CreateDeptDto, type UpdateDeptDto, DeptTree } from '~/services/dept.service';
import { COMMON_STATUS, CommonStatus } from '@nbase/shared';
import { formatDateTime, formatStatusLabel, getStatusColor } from '~/utils/format';
import { INPUT_WIDTH, TABLE_COLUMN_WIDTH } from '~/constants';

/**
 * 部门管理页面
 */
const DeptManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<Dept[]>([]);
  const [deptTree, setDeptTree] = useState<DeptTree[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalForm] = Form.useForm();
  const [editingId, setEditingId] = useState<string | null>(null);

  /**
   * 加载部门树
   */
  const loadDeptTree = async () => {
    try {
      setLoading(true);
      const tree = await deptService.getTree();
      setDeptTree(tree);
      setDataSource(tree);
    } catch {
      // 错误已由 request.ts 统一处理
    } finally {
      setLoading(false);
    }
  };

  /**
   * 初始化加载
   */
  useEffect(() => {
    loadDeptTree();
  }, []);

  /**
   * 打开新增/编辑弹窗
   */
  const handleOpenModal = (record?: Dept) => {
    if (record) {
      setEditingId(record.id);
      modalForm.setFieldsValue(record);
    } else {
      setEditingId(null);
      modalForm.resetFields();
    }
    setModalVisible(true);
  };

  /**
   * 关闭弹窗
   */
  const handleCloseModal = () => {
    setModalVisible(false);
    setEditingId(null);
    modalForm.resetFields();
  };

  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    try {
      const values = await modalForm.validateFields();
      if (editingId) {
        await deptService.update(editingId, values as UpdateDeptDto);
        message.success('更新成功');
      } else {
        await deptService.create(values as CreateDeptDto);
        message.success('创建成功');
      }
      handleCloseModal();
      loadDeptTree();
    } catch {
      // 表单验证失败或请求失败，错误已由相应模块处理
    }
  };

  /**
   * 删除
   */
  const handleDelete = async (id: string) => {
    try {
      await deptService.delete(id);
      message.success('删除成功');
      loadDeptTree();
    } catch {
      // 错误已由 request.ts 统一处理
    }
  };

  /**
   * 转换部门树为 TreeSelect 数据
   */
  const convertToTreeSelectData = (depts: DeptTree[]): any[] => {
    return depts.map((dept) => ({
      title: dept.name,
      value: dept.id,
      children: dept.children ? convertToTreeSelectData(dept.children) : undefined,
    }));
  };

  /**
   * 表格列定义
   */
  const columns: TableColumnsType<Dept> = [
    {
      title: '部门名称',
      dataIndex: 'name',
      key: 'name',
      width: TABLE_COLUMN_WIDTH.PATH,
    },
    {
      title: '部门编码',
      dataIndex: 'code',
      key: 'code',
      width: TABLE_COLUMN_WIDTH.DESCRIPTION,
    },
    {
      title: '负责人',
      dataIndex: 'leader',
      key: 'leader',
      width: TABLE_COLUMN_WIDTH.NAME,
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
      width: TABLE_COLUMN_WIDTH.DESCRIPTION,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: TABLE_COLUMN_WIDTH.DATETIME,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: TABLE_COLUMN_WIDTH.STATUS,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: TABLE_COLUMN_WIDTH.STATUS,
      render: (status: number) => (
        <Tag color={getStatusColor(status as CommonStatus)}>{formatStatusLabel(status as CommonStatus)}</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: TABLE_COLUMN_WIDTH.DATETIME,
      render: (text: string) => formatDateTime(text),
    },
    {
      title: '操作',
      key: 'action',
      width: TABLE_COLUMN_WIDTH.ACTIONS,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleOpenModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        {/* 操作按钮 */}
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => handleOpenModal()}>
            新增部门
          </Button>
        </div>

        {/* 表格 */}
        <Table
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          loading={loading}
          pagination={false}
          scroll={{ x: 1400 }}
        />
      </Card>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={editingId ? '编辑部门' : '新增部门'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={handleCloseModal}
        width={600}
      >
        <Form form={modalForm} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
          <Form.Item name="parentId" label="上级部门">
            <TreeSelect
              placeholder="请选择上级部门"
              allowClear
              treeData={convertToTreeSelectData(deptTree)}
              treeDefaultExpandAll
            />
          </Form.Item>
          <Form.Item
            name="name"
            label="部门名称"
            rules={[{ required: true, message: '请输入部门名称' }]}
          >
            <Input placeholder="请输入部门名称" />
          </Form.Item>
          <Form.Item
            name="code"
            label="部门编码"
            rules={[{ required: true, message: '请输入部门编码' }]}
          >
            <Input placeholder="请输入部门编码" disabled={!!editingId} />
          </Form.Item>
          <Form.Item name="leader" label="负责人">
            <Input placeholder="请输入负责人" />
          </Form.Item>
          <Form.Item name="phone" label="联系电话">
            <Input placeholder="请输入联系电话" />
          </Form.Item>
          <Form.Item name="email" label="邮箱">
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item name="sort" label="排序" initialValue={0}>
            <InputNumber min={0} style={{ width: INPUT_WIDTH.FULL }} />
          </Form.Item>
          <Form.Item name="description" label="描述">
            <Input.TextArea placeholder="请输入描述" rows={3} />
          </Form.Item>
          <Form.Item name="status" label="状态" initialValue={COMMON_STATUS.ACTIVE}>
            <Select>
              <Select.Option value={COMMON_STATUS.ACTIVE}>启用</Select.Option>
              <Select.Option value={COMMON_STATUS.DISABLED}>禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DeptManagement;

